// pages/b50printer/printer.js
var lpapi = require('../utils/lpapi');
const nfcService = require('../service/nfc-service');
import {
    QRCodeModel,
    QRUtil
} from "../utils/common/qrcode";

var app = getApp()
var tempIndex = 0;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        canvas: null,
        canvasId: "test",
        printDisabled: true,
        printTemplateArr: ['大码', '小码'],
        templateIndex: 0,
        canvasWidth: 40,
        canvasHeight: 20
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        let that = this
        wx.createSelectorQuery()
            .select('#' + that.data.canvasId) // 在 WXML 中填入的 id
            .node(({
                node: canvasObj
            }) => {
                that.data.canvas = canvasObj.getContext('2d')
                console.log("获取画布:", that.data.canvas)
            })
            .exec()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    bindPickerChangeTemplate(e) {
        this.setData({
            templateIndex: e.detail.value
        })
    },

    printOneLabel: function (rfid, equNum) {
        let width = 40
        let height = 20
        if(this.data.templateIndex == 1) {
            width = 20
            height = 10
        }
        let that = this
        that.data.printIndex = that.data.printIndex + 1
        let leftCount = that.data.printTotalCounts - that.data.printIndex
        console.log("剩余的数量A:", leftCount)
        if (leftCount < 0) {
            wx.hideLoading({
                success: (res) => {},
            })
            wx.showToast({
                title: '打印成功',
                icon: '',
                image: '',
                duration: 2000,
                mask: true,
            })
        } else {
            const ctx = that.data.canvas;
            ctx.clearRect(0, 0, that.data.canvasWidth, that.data.canvasHeight)
            lpapi.startDrawLabel(that, width, height, 0);
            that.data.canvas.lineWidth = '4'
            // let rfid = '5440010F'
            let rfidLeft = 18
            let rfidTop = 6.5
            // let equNum = 'L109527'
            let equLeft = 18
            let equTop = 11
            let equFontHeight = 3
            var code = rfid;
            if(that.data.templateIndex == 1) {
                rfidLeft = 9
                rfidTop = 4
                equLeft = 9
                equTop = 6
                equFontHeight = 2
            }
            that.draw(code)
            lpapi.drawText(rfid, rfidLeft, rfidTop, equFontHeight)
            lpapi.drawText(equNum, equLeft, equTop, equFontHeight)

            lpapi.endDrawLabel(function () {
                lpapi.print(function () {
                    console.log("剩余的数量:", leftCount, ctx.width, ctx.height)
                    let equRfid = that.data.equRfidList[that.data.printIndex]
                    if (equRfid) {
                        let equNum = 'L' + equRfid.equNum
                        let rfid = equRfid.rfid
                        console.log("接着打印:", equNum, rfid, that.data.printIndex)
                        setTimeout(() => {
                            that.printOneLabel(rfid, equNum)
                        }, 1500);
                    }
                })
            })
        }


    },

    inputStartCode(e) {
        let input = e.detail.value
        let regex = /^\d+$/;
        if (!regex.test(input)) {
            wx.showToast({
                title: '请输入数字',
            })
            this.setData({
                errStartColor: 'border:1px solid red;'
            })
            return
        }

        this.data.startEquCode = e.detail.value

        if (this.data.endEquCode && this.data.endEquCode < input) {
            this.setData({
                errStartColor: 'border:1px solid red;'
            })
            wx.showToast({
                title: '起始不可大于结束',
            })
            return
        }
        this.setData({
            errStartColor: '',
            errEndColor: ''
        })
    },
    inputEndCode(e) {
        let input = e.detail.value
        let regex = /^\d+$/;
        if (!regex.test(input)) {
            wx.showToast({
                title: '请输入数字',
            })
            this.setData({
                errEndColor: 'border:1px solid red;'
            })
            return
        }

        this.data.endEquCode = e.detail.value

        if (this.data.startEquCode && this.data.startEquCode > input) {
            this.setData({
                errEndColor: 'border:1px solid red;'
            })
            wx.showToast({
                title: '结束不可小于起始',
            })
            return
        }
        this.setData({
            errStartColor: '',
            errEndColor: ''
        })
    },
    openPrinter() {
        let that = this
        console.log("打印机连接----》")
        wx.showLoading({
            title: '连接打印机',
        })

        lpapi.openPrinter('', function (res) {

            console.log('名字：' + lpapi.connectingPrinterDetailInfos().name);
            console.log('DPI：' + lpapi.connectingPrinterDetailInfos().DPI);
            console.log('打印宽度：' + lpapi.connectingPrinterDetailInfos().width);

            wx.hideLoading({
                success: (res) => {},
            })

            that.setData({
                printDisabled: false
            })

            wx.showToast({
                title: '连接打印机成功',
                icon: '',
                image: '',
                duration: 2000,
                mask: true,
                success: function (res) {},
                fail: function (res) {},
                complete: function (res) {},
            })

        }, function () {
            that.setData({
                printDisabled: true
            })
            wx.showToast({
                title: '打印机连接断开',
                icon: '',
                image: '',
                duration: 2000,
                mask: true,
                success: function (res) {},
                fail: function (res) {},
                complete: function (res) {},
            })
        })
    },

    disconnect: function () {
        app.globalData._that = this
        lpapi.closePrinter();

        // wx.closeBluetoothAdapter({
        //   success: (res) => {
        //   },
        // })
    },

    print: function () {
        if (!this.data.startEquCode || !this.data.endEquCode || this.data.startEquCode > this.data.endEquCode) {
            wx.showToast({
                title: '编号错误',
            })
            return
        }

        wx.showLoading({
            title: '打印中',
        })

        let that = this

        nfcService.getRfids({
            "startNum": that.data.startEquCode,
            "endNum": that.data.endEquCode
        }, (data) => {
            //TODO 从服务器根据编号起始结束获取唯一对应的rfid
            console.log("获取rfid信息:", data)
            that.data.equRfidList = data.data

            that.data.printTotalCounts = that.data.endEquCode - that.data.startEquCode + 1
            that.data.printIndex = 0
            let equRfid = that.data.equRfidList[that.data.printIndex]
            let equNum = 'L' + equRfid.equNum
            let rfid = equRfid.rfid
            console.log("打印:", equNum, rfid, that.data.printIndex)
            that.printOneLabel(rfid, equNum);
        })

    },

    async draw(url) {
        // 获取canvas以及context
        // const canvas = this.data.canvas;
        const ctx = this.data.canvas;
        // 二维码的颜色
        const colorDark = '#000';
        // 获取二维码的大小，因css设置的为750rpx，将其转为px
        const rawViewportSize = this.data.canvasHeight * 0.6;
        // 二维码容错率{ L: 1, M: 0, Q: 3, H: 2 }
        const correctLevel = 2;

        // 创建二维码实例对象，并添加数据进行生成
        const qrCode = new QRCodeModel(-1, correctLevel);
        qrCode.addData(url);
        qrCode.make();

        //距离画布左边距离
        const left = 20;
        //距离画布右边距离
        const top = 14;
        // 每个方向的二维码数量
        const nCount = qrCode.moduleCount;
        // 计算每个二维码方块的大小
        const nSize = getRoundNum(rawViewportSize / nCount, 3)
        // 每块二维码点的大小比例
        const dataScale = 1;
        // 计算出dataScale不为1时，每个点的偏移值
        const dataXyOffset = (1 - dataScale) * 0.5;

        // 二重循环，绘制每一个点
        for (let row = 0; row < nCount; row++) {
            for (let col = 0; col < nCount; col++) {
                // row 和 col 处的模块是否是黑色区
                const bIsDark = qrCode.isDark(row, col);
                // 是否是二维码的图案定位标识区 Position Detection Pattern（如本模块，是三个顶点位置处的大方块）
                const isBlkPosCtr = (col < 8 && (row < 8 || row >= nCount - 8)) || (col >= nCount - 8 && row < 8);
                // 是否是Timing Patterns，也是用于协助定位扫描的
                const isTiming = (row == 6 && col >= 8 && col <= nCount - 8) || (col == 6 && row >= 8 && row <= nCount - 8);
                // 如果是这些区域 则不进行绘制
                let isProtected = isBlkPosCtr || isTiming;

                // 计算每个点的绘制位置（left，top）
                const nLeft = col * nSize + (isProtected ? 0 : dataXyOffset * nSize);
                const nTop = row * nSize + (isProtected ? 0 : dataXyOffset * nSize);
                // 描边色、线宽、填充色配置
                ctx.strokeStyle = colorDark;
                ctx.lineWidth = 0.5;
                ctx.fillStyle = bIsDark ? colorDark : "rgba(255, 255, 255, 0.6)";
                // 如果不是标识区，则进行绘制
                if (!isProtected) {
                    ctx.fillRect(
                        nLeft + left,
                        nTop + top,
                        (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize,
                        (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize
                    );
                }
            }
        }
        // 绘制Position Detection Pattern
        ctx.fillStyle = colorDark;
        ctx.fillRect(0 + left, 0 + top, 7 * nSize, nSize);
        ctx.fillRect((nCount - 7) * nSize + left, 0 + top, 7 * nSize, nSize);
        ctx.fillRect(0 + left, 6 * nSize + top, 7 * nSize, nSize);
        ctx.fillRect((nCount - 7) * nSize + left, 6 * nSize + top, 7 * nSize, nSize);
        ctx.fillRect(0 + left, (nCount - 7) * nSize + top, 7 * nSize, nSize);
        ctx.fillRect(0 + left, (nCount - 7 + 6) * nSize + top, 7 * nSize, nSize);
        ctx.fillRect(0 + left, 0 + top, nSize, 7 * nSize);
        ctx.fillRect(6 * nSize + left, 0 + top, nSize, 7 * nSize);
        ctx.fillRect((nCount - 7) * nSize + left, 0 + top, nSize, 7 * nSize);
        ctx.fillRect((nCount - 7 + 6) * nSize + left, 0 + top, nSize, 7 * nSize);
        ctx.fillRect(0 + left, (nCount - 7) * nSize + top, nSize, 7 * nSize);
        ctx.fillRect(6 * nSize + left, (nCount - 7) * nSize + top, nSize, 7 * nSize);
        ctx.fillRect(2 * nSize + left, 2 * nSize + top, 3 * nSize, 3 * nSize);
        ctx.fillRect((nCount - 7 + 2) * nSize + left, 2 * nSize + top, 3 * nSize, 3 * nSize);
        ctx.fillRect(2 * nSize + left, (nCount - 7 + 2) * nSize + top, 3 * nSize, 3 * nSize);
        // 绘制Position Detection Pattern 完毕

        // 绘制Timing Patterns
        const timingScale = 1;
        const timingXyOffset = (1 - timingScale) * 0.5;
        for (let i = 0; i < nCount - 8; i += 2) {
            _drawDot(ctx, 8 + i, 6, nSize, timingXyOffset, timingScale, left, top);
            _drawDot(ctx, 6, 8 + i, nSize, timingXyOffset, timingScale, left, top);
        }
        // 绘制Timing Patterns 完毕
    },
})

function getRoundNum(num, fixedNum = 0) {
    return Number(num.toFixed(fixedNum))
}

function getPxFromRpx(rpx) {
    const screenWidth = wx.getSystemInfoSync()['screenWidth'];
    return Math.round(rpx * screenWidth / 750);
}

function _drawDot(canvasContext, centerX, centerY, nSize, xyOffset = 0, dotScale = 1, left, top) {
    canvasContext.fillRect(
        (centerX + xyOffset) * nSize + left,
        (centerY + xyOffset) * nSize + top,
        dotScale * nSize,
        dotScale * nSize
    );
}